package com.huimin.merchant.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huimin.merchant.convert.MerchantConvert;
import com.huimin.merchant.dto.MerchantDTO;
import com.huimin.merchant.dto.StaffDTO;
import com.huimin.merchant.dto.StoreDTO;
import com.huimin.merchant.entity.Merchant;
import com.huimin.merchant.entity.Staff;
import com.huimin.merchant.entity.Store;
import com.huimin.merchant.entity.StoreStaff;
import com.huimin.merchant.mapper.MerchantMapper;
import com.huimin.merchant.mapper.StaffMapper;
import com.huimin.merchant.mapper.StoreMapper;
import com.huimin.merchant.mapper.StoreStaffMapper;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.user.api.TenantService;
import com.huiminpay.user.api.dto.tenant.CreateTenantRequestDTO;
import com.huiminpay.user.api.dto.tenant.TenantDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author ymx
 * @date 2020-12-01 04:09:04
 */
@Service
@Slf4j

public class MerchantServiceImpl implements MerchantServiceApi {


	@Autowired
	private MerchantMapper merchantMapper;

	@Autowired
	private StoreMapper storeMapper;

	@Autowired
	private StaffMapper staffMapper;

	@Autowired
	private StoreStaffMapper storeStaffMapper;

	@Reference
	private TenantService tenantService;

	/**
	 * 通过ID查询Merchant
	 *
	 * @param id MerchantId
	 * @return dto
	 */
	@Override
	public MerchantDTO findMerchantById(Long id) {
		Merchant merchant = merchantMapper.selectById(id);
		MerchantDTO merchantDTO = new MerchantDTO();
		BeanUtils.copyProperties(merchant, merchantDTO);
		return merchantDTO;
	}

	/**
	 * 商户注册
	 *
	 * @param merchantDTO dto
	 *                    \@Transactional 开启事务
	 */
	@Override
	@Transactional(rollbackFor = BusinessException.class)
	public MerchantDTO registerMerchant(MerchantDTO merchantDTO) {
		// TODO: 2020/12/2  校验修改
		if (merchantDTO == null) {
			throw new RuntimeException("参数非法！");
		}
		if (StringUtils.isEmpty(merchantDTO.getMobile())) {
			throw new RuntimeException("电话参数非法！");
		}

		// 惠民支付对接saas
		CreateTenantRequestDTO createTenantRequestDTO = new CreateTenantRequestDTO();
		createTenantRequestDTO.setMobile(merchantDTO.getMobile());
		createTenantRequestDTO.setBundleCode("huimin-merchant");
		createTenantRequestDTO.setName(merchantDTO.getUsername());
		createTenantRequestDTO.setPassword(merchantDTO.getPassword());
		createTenantRequestDTO.setTenantTypeCode("huimin-merchant");
		TenantDTO tenantAndAccount = tenantService.createTenantAndAccount(createTenantRequestDTO);

		// 变化形态
		Merchant merchant = MerchantConvert.INSTANCE.dto2Entity(merchantDTO);
		merchant.setAuditStatus("0");//审核状态 0-未申请,1-已申请待审核,2-审核通过,3-审核拒绝
		merchant.setTenantId(tenantAndAccount.getId()); // 设置租户id


		merchantMapper.insert(merchant);

		// 新增门店信息
		StoreDTO storeDTO = new StoreDTO();
		storeDTO.setMerchantId(merchant.getId());
		storeDTO.setStoreName("根门店");
		StoreDTO storeDTO1 = addStore(storeDTO);

		StaffDTO staffDTO = new StaffDTO();
		staffDTO.setMerchantId(merchant.getId());
		staffDTO.setMobile(merchantDTO.getMobile());
		staffDTO.setUsername(merchantDTO.getUsername());
		// 新增员工信息
		StaffDTO staffDb = createStaff(staffDTO);
		// 绑定员工与门店的关系
		bindStaffForStore(staffDb.getId(), storeDTO1.getId());


		merchantDTO.setId(merchant.getId());


		return merchantDTO;
	}

	/**
	 * 根据手机号获取商户存在信息
	 *
	 * @param mobile 手机号
	 * @ 商户信息
	 */
	@Override
	public void findMerchantByPhone(String mobile) {
		Integer count = merchantMapper.selectCount(new LambdaQueryWrapper<Merchant>().eq(Merchant::getMobile, mobile));
		if (count > 0) {
			throw new BusinessException(CommonErrorCode.E_200203);
		}
	}

	/**
	 * 资质申请
	 *
	 * @param merchantId  商户id
	 * @param merchantDTO 资质申请信息
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void applyMerchant(Long merchantId, MerchantDTO merchantDTO) {
		// 传入参数空值判断,空时抛出
		if (merchantDTO == null || merchantId == null) {
			throw new BusinessException(CommonErrorCode.E_200202);
		}

		// 商户是否存在判断，不存在时抛出
		Merchant merchantDb = merchantMapper.selectById(merchantId);
		if (merchantDb == null) {
			throw new BusinessException(CommonErrorCode.E_200227);
		}

		// 将DTO转为entity,并设置merchantId/mobile/status后更新数据库
		Merchant entity = MerchantConvert.INSTANCE.dto2Entity(merchantDTO);
		entity.setId(merchantId);
		entity.setMobile(merchantDb.getMobile());
		entity.setAuditStatus("1");//审核状态 0-未申请,1-已申请待审核,2-审核通过,3-审核拒绝

		merchantMapper.updateById(entity);


	}

	/**
	 * 添加门店
	 *
	 * @param storeDTO storeDTO
	 * @return StoreDTO
	 */
	@Override
	public StoreDTO addStore(StoreDTO storeDTO) {
		Store store = new Store();
		BeanUtils.copyProperties(storeDTO, store);
		storeMapper.insert(store);

		storeDTO.setId(store.getId());
		return storeDTO;
	}

	/**
	 * 添加员工
	 *
	 * @param staffDTO 员工对象
	 * @return 员工对象
	 */
	@Override
	public StaffDTO createStaff(StaffDTO staffDTO) {
		Staff staff = new Staff();
		BeanUtils.copyProperties(staffDTO, staff);
		staffMapper.insert(staff);
		staffDTO.setId(staff.getId());
		return staffDTO;
	}

	/**
	 * 绑定员工与门店的关系
	 *
	 * @param staffId 员工id
	 * @param storeId 门店id
	 * @return 绑定确认
	 */
	@Override
	public Boolean bindStaffForStore(Long staffId, Long storeId) {
		try {
			StoreStaff storeStaff = new StoreStaff();
			storeStaff.setStaffId(staffId);
			storeStaff.setStoreId(storeId);
			storeStaffMapper.insert(storeStaff);
			return true;
		} catch (Exception e) {
			// log.error(e.getMessage());
			return false;
		}

	}
}
